package com.gongpingjialoan.activity.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.sell.SellPrivateActivity;
import com.gongpingjialoan.activity.sell.WantSellCarActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.StepRecord;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.AccurateDialog;
import com.gongpingjialoan.widget.LoadingDialog;

/**
 * html url 公用页面
 * <p/>
 * 参数： url :如果url不为空 展示url地址页面； content:如果content 不为空 展示内content内容； title: 不能为空 页面标题；
 *
 * @author huankang
 */
@SuppressLint("NewApi")
public class WebActivity extends BaseActivity  {

    private WebActivity mySelf = this;

    private WebView webView;

    private TextView title_txt;
    private ImageView title_right;
    private final int RESULT_CONTACT = 1;

    private final int RESULT_LOGIN = 2;

    public static final int WANTSELL = 3;

    public String url = "";

    private UserManager mUserManager;


    private LoadingDialog loadingDialog;

    private AssessmentData ad = AssessmentData.getInstance();

    private String fromType;

    private String pricetype = "";


    private String loadurl;

    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }


    @Override
    public void onBackPressed() {
        //表示从推送而来
        if (MyPushIntentService.RECKON.equals(fromType)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void initTitleBar() {
        View backV = findViewById(R.id.title_back);
        if (backV != null) {
            backV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    onBackPressed();
                }
            });
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        action = "eval_sell";
        super.onCreate(savedInstanceState);
        loadingDialog = new LoadingDialog(mySelf);
//        mDomainSelectDialog = new DomainSelectDialog(this);
        setContentView(R.layout.web_main);
        initView();
        hander.sendEmptyMessage(SHOW_PROCESS);
    }



    private void initView() {
        title_txt = (TextView) this.findViewById(R.id.top_title);
        title_right = (ImageView) this.findViewById(R.id.right_accuracy);
        title_right.setVisibility(View.VISIBLE);
        title_right.setBackgroundResource(R.drawable.juedebuzhun);
        title_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AccurateDialog accurateDialog = new AccurateDialog(WebActivity.this);
                accurateDialog.setOnPickResultListener(new AccurateDialog.OnPickResultListener() {

                    @Override
                    public void onResult(int result) {
                        if (result == 1) {
//                            title_right.setBackgroundResource(R.drawable.yitijiao);
//                            title_right.setEnabled(false);
                        }
                    }
                });
                accurateDialog.show();
            }
        });
        title_txt.setText("估值报告");
        Bundle bundle = this.getIntent().getExtras();
        fromType = bundle.getString("type", "");
        //推送用
        String source = bundle.getString("source", "");
        String job_id = bundle.getString("job_id", "");
        if (fromType.equals(MyPushIntentService.RECKON)) {
            String vaule = bundle.getString("typevalue", "");
            StepRecord.recordStep(this, "pushnotification", "{type:" + fromType + ",typevalue:" + vaule + ",source:" + source + ",job_id:" + job_id + "}");
            setAssessmentData(vaule);
            url = API.assessCarUrl + vaule;
        } else {
            url = bundle.getString("url");
        }


        mUserManager = new UserManager(mySelf);
        mUserManager = mUserManager.LoadUserInfo();

        webView = ((WebView) mySelf.findViewById(R.id.web_view));
        webView.setDownloadListener(new MyWebViewDownLoadListener());
        // webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        webView.setWebViewClient(new MyWebViewClient());
        // webView.setWebChromeClient(new MyChromeClient());
        webView.setBackgroundColor(Color.parseColor("#FFFFFF"));
        WebSettings webSettings = webView.getSettings();
        // 是否允许在webview中执行javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setUseWideViewPort(true);
        webView.addJavascriptInterface(this, "GPJJSNEW");
        webView.loadUrl("javascript:function()");
        // 支持jsp页面javaScript函数

        loadurl = url + "?city=" + ad.getCity() + "&version="
                + GPJApplication.getInstance().getVersion();
        Utils.LogD(loadurl);
        webView.postDelayed(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(loadurl);
            }
        }, 1000);


    }



    //brand/model/modeldetail/year-month/mileage,形如audi/audi-a4/3621_ah/2008-4/2.50/nanjing
    public void setAssessmentData(String value) {
        try {
            String[] datas = value.split("/");
            ad.setBrandSlug(datas[0]);
            ad.setBrandName(datas[0]);
            ad.setModelSlug(datas[1]);
            ad.setModelName("");
            ad.setModelDetailName(getIntent().getStringExtra("description"));
            ad.setModelDetailSlug(datas[2]);
            ad.setMile(datas[4]);
            ad.setCity(getIntent().getStringExtra("city"));
            ad.setStatus("");
            ad.setCar_id("");
            String times[] = datas[3].split("-");
            ad.setYear(times[0]);
            ad.setMonth(times[1]);

        } catch (Exception e) {

        }
    }


    @Override
    protected void onDestroy() {
        action = "eval_sell";
        super.onDestroy();
        hander.removeMessages(0);
        webView.loadUrl("");
    }





    class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            hander.sendEmptyMessage(HIDE_PROCESS);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("tel:")) {
                String phone = getPhoneNumber(url);
                if (TextUtils.isEmpty(phone)) {
                    return false;
                } else {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                    startActivity(intent);
                    return true;
                }
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }


    private String getPhoneNumber(String url) {
        String phones[] = url.split(":");
        if (phones.length == 2) {
            return phones[1];
        }
        return "";
    }


    @JavascriptInterface
    public void assSubmitNEW(String parmes) {
        StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_sell_submit", System.currentTimeMillis(), 1f));
        // hander.removeMessages(0);
        String new_brand = "";
        String new_model = "";
        String new_model_detail = "";

        String condition = "";
        String evalprice = "";
        if (parmes.split(",").length >= 5) {
            new_brand = parmes.split(",")[0];
            new_model = parmes.split(",")[1];
            new_model_detail = parmes.split(",")[2];
            pricetype = parmes.split(",")[3];
            evalprice = parmes.split(",")[4];
            condition = "good";
            // System.out.println("web  eval_price" + eval_price);
        }
        ad.setStatus(condition);
        ad.setEval_price(evalprice);
        ad.setPricetype(pricetype);
        ad.setNew_brand(new_brand);
        ad.setNew_model(new_model);
        ad.setNew_model_detail(new_model_detail);
        ad.from = getIntent().getBooleanExtra("isassessment", true);

        if (GPJApplication.getInstance().isLogin()) {
            Intent intent = null;
            if("private_party".equals(pricetype)){
                intent = new Intent(this, SellPrivateActivity.class);
            }else {
                intent = new Intent(this, WantSellCarActivity.class);
            }
            startActivity(intent);
        } else {
            // 没有登陆
            Intent it = new Intent(mySelf, LoginActivity.class);
            startActivityForResult(it, RESULT_LOGIN);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Intent intent = null;
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {

                case RESULT_LOGIN:
                    if("private_party".equals(pricetype)){
                        intent = new Intent(this, SellPrivateActivity.class);
                    }else {
                        intent = new Intent(this, WantSellCarActivity.class);
                    }
                    startActivity(intent);
                    break;
                case RESULT_CONTACT:
                    intent = getIntent();
                    setResult(Activity.RESULT_OK, intent);
                    mySelf.finish();
                    break;
                case WANTSELL:
                    finish();
                    break;
                default:
                    break;
            }
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == SHOW_PROCESS) {
                loadingDialog.show();
            } else if (msg.what == HIDE_PROCESS) {
                loadingDialog.hide();
            }
        }
    };


    private static final int SHOW_PROCESS = 123;
    private static final int HIDE_PROCESS = 124;

}